from datetime import timezone
from typing import re

from django.core.exceptions import ValidationError
from django.shortcuts import render

# Create your views here.
from django.shortcuts import render
from django.http import response
from django.http.response import HttpResponseRedirect
from django.shortcuts import render, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import redirect
from django.http import HttpResponse
from django.db import models
from user.models import *
from django import forms
from django.contrib import messages


# 登录界面
def load(request):
    if request.method == "POST":
        no_post = request.POST.get('no')
        password = request.POST.get('password')
        identy = request.POST.get('identy')
        if Register.objects.filter(no=no_post).exists():
            if Register.objects.get(no=no_post).password == password:
                if (identy == Register.objects.get(no=no_post).get_role_display()) & (identy == "teacher"):
                    student = Student.objects.all()
                    form_stu = UserStudent()
                    request.session['user'] = no_post

                    return render(request, 'show_student_tea.html',
                                  {"student": student, "form": form_stu, "user": no_post})
                if (identy == Register.objects.get(no=no_post).get_role_display()) & (identy == "student"):
                    form_course = UserTea_Cour()
                    # 课程号
                    user_courses = Stu_Cour.objects.filter(sno=no_post).values_list('cno', flat=True)
                    # 获取最终的课程信息
                    course = Tea_Cour.objects.filter(cno__in=user_courses)
                    request.session['user'] = no_post

                    return render(request, 'show_course_stu.html', {
                        'course_data': course,
                        "form_course": form_course,
                        "user": no_post
                    })
                else:
                    return render(request, 'login.html', {'error_message': '身份信息错误'})

            else:
                return render(request, 'login.html', {'error_message': '账户名或密码错误'})
        else:
            return render(request, 'login.html', {'error_message': '用户不存在'})

    if request.method == "GET":
        return render(request, 'login.html')


# 用户注册类
class UserRegister(forms.ModelForm):
    class Meta:
        model = Register
        fields = ['no', 'username', 'password', 'tel', 'role']
        widgets = {
            "no": forms.TextInput(attrs={'class': 'form-control'}),
            "username": forms.TextInput(attrs={'class': "form-control"}),
            "password": forms.TextInput(attrs={'class': "form-control"}),
            "tel": forms.TextInput(attrs={'class': "form-control"}),
            "role": forms.Select(attrs={'class': "form-control"}),
        }


def register(request):
    if request.method == "GET":
        form = UserRegister()
        return render(request, 'register.html', {"form": form})
    if request.method == "POST":
        form = UserRegister(request.POST)
        if form.is_valid():
            # 教师注册
            if form.cleaned_data.get('role'):
                if Teacher.objects.filter(tno=form.cleaned_data.get('no')).exists():
                    form.save()
                    return render(request, 'register.html')
                else:
                    return render(request, 'register.html',
                                  {"user_no": "用户信息不存在，请通知管理员添加！", "form": form})
            else:  # 学生注册
                if Student.objects.filter(sno=form.cleaned_data.get('no')).exists():
                    form.save()
                    return render(request, 'register.html')
                else:
                    return render(request, 'register.html',
                                  {"user_no": "用户信息不存在，请通知管理员添加！", "form": form})
        else:
            return render(request, 'register.html', {"form": form})


class UserStudent(forms.ModelForm):
    class Meta:
        model = Student
        fields = ['sno', 'name', 'sgrade', 'department']
        widgets = {
            "sno": forms.TextInput(attrs={'class': "form-control", 'style': "width:90%;"}),
            "name": forms.TextInput(attrs={'class': "form-control", 'style': "width:90%;"}),
            "sgrade": forms.Select(attrs={'class': "form-control", 'style': "width:90%;"}),
            "department": forms.Select(attrs={'class': "form-control", 'style': "width:90%;"}),
        }


def showStu_tea(request):
    user = request.session.get('user')
    data_dict = {}
    if request.method == "GET":
        sno = request.GET.get('sno', "")
        name = request.GET.get('name', "")
        sgrade = request.GET.get('sgrade')
        department = request.GET.get('department', "")
        if sno:
            data_dict['sno'] = sno
        if name:
            data_dict['name'] = name
        if sgrade:
            data_dict['sgrade'] = sgrade
        if department:
            data_dict['department'] = department
        form = UserStudent(request.GET)
        student = Student.objects.filter(**data_dict)
        return render(request, 'show_student_tea.html', {'student': student, "form": form, "user": user})
    else:
        form = UserStudent()
        student = Student.objects.all()
        return render(request, 'show_student_tea.html', {'student': student, "form": form, "user": user})


def addStu_tea(request):
    user = request.session.get('user')
    print(request.method)
    if request.method == "GET":
        form = UserStudent()
        return render(request, 'add_student.html', {'form': form, "user": user})
    else:
        form = UserStudent(request.POST)
        if form.is_valid():
            form.save()
            return render(request, 'add_student.html', {'form': form, 'success': "学生信息添加成功", "user": user})
        else:
            return render(request, 'add_student.html', {'form': form, "user": user})


def deleteStu_tea(request):
    sno = request.GET.get('sno')
    Student.objects.filter(sno=sno).delete()
    return redirect('stu_information_tea')


class UserTea_Cour_Cname(forms.ModelForm):
    class Meta:
        model = Tea_Cour
        fields = ['cname', ]
        widgets = {
            "cname": forms.TextInput(attrs={'class': "form-control", 'style': "width:90%;"'requ'}),
        }

        # 考试管理


class UserTest(forms.ModelForm):
    class Meta:
        model = Test_ddl
        fields = ['cno', 'test_time', 'test_place']
        widgets = {
            "cno": forms.TextInput(attrs={'class': "form-control", 'style': "width:90%;"}),
            "test_time": forms.DateInput(
                attrs={'class': "form-control", 'type': 'date', 'style': "width:90%;"}),
            "test_place": forms.TextInput(attrs={'class': "form-control", 'style': "width:90%;"}),
        }



def showTest_tea(request):
    print(request.method)
    user = request.session.get('user')
    data_dict = {}
    if request.method == "GET":
        cno = request.GET.get('cno', "")
        test_time = request.GET.get('test_time', "")
        test_place = request.GET.get('test_place', "")
        cname = request.GET.get('cname', "")

        # Collect filter criteria based on the query parameters
        if cno:
            data_dict['cno'] = cno
        if test_time:
            data_dict['test_time'] = test_time
        if test_place:
            data_dict['test_place'] = test_place

        # Retrieve tests based on the collected criteria
        if cname:
            course_cno = Tea_Cour.objects.filter(cname=cname).values_list('cno', flat=True)
            test = Test_ddl.objects.filter(cno__in=course_cno, **data_dict)
        else:
            test = Test_ddl.objects.filter(**data_dict)

        # Retrieve course names for the current teacher
        course_names_dict = {course.cno: course.cname for course in Tea_Cour.objects.filter(tno=user)}

        # Initialize forms with GET data
        form_test = UserTest(request.GET)
        form_course = UserTea_Cour_Cname(request.GET)

        return render(request, 'show_test_tea.html', {
            'test': test,
            'cname': course_names_dict,
            "form_test": form_test,
            "form_course": form_course,
            "user": user
        })


def addTest_tea(request):
    print(request.method)
    user = request.session.get('user')
    if request.method == "GET":
        cno = request.GET.get('cno', "")
        cname = request.GET.get('cname', "")
        form_test = UserTest(initial={'cno': cno})
        form_course = UserTea_Cour_Cname(initial={'cname': cname})
        return render(request, 'add_test.html', {'form_test': form_test, 'form_course': form_course, "user": user})
    elif request.method == "POST":
        form_test = UserTest(request.POST)
        form_course = UserTea_Cour_Cname(request.POST)
        if form_course.is_valid() and form_test.is_valid():
            cname = form_course.cleaned_data.get('cname')
            cno = form_test.cleaned_data.get('cno')
            if not Tea_Cour.objects.filter(cno=cno, cname=cname).exists():
                return render(request, 'add_test.html',
                              {'form_test': form_test, 'form_course': form_course, 'errormessage': "该课程不存在",
                               "user": user})
            if Test_ddl.objects.filter(cno=cno).exists():
                return render(request, 'add_test.html',
                              {'form_test': form_test, 'form_course': form_course,
                               'errormessage': "该课程考试已经存在",
                               "user": user})
            else:
                print("ok")
                form_test.save()
                return render(request, 'add_test.html',
                              {'form_test': form_test, 'form_course': form_course,
                               'success': "考试发布成功，请返回查看！",
                               "user": user})  # 重定向到添加考试页面，以便清空表单内容
        else:
            print(form_course.errors)
            return render(request, 'add_test.html', {'form_test': form_test, 'form_course': form_course, "user": user})
    else:
        print("o1k")
        form_test = UserTest(request.POST)
        form_course = UserTea_Cour_Cname(request.POST)
        # 处理不支持的请求方法
        return render(request, 'add_test.html', {'form_test': form_test, 'form_course': form_course, "user": user})


def deleteTest_tea(request):
    cno = request.GET.get('cno')
    Test_ddl.objects.filter(cno=cno).delete()
    return redirect('test_information_tea')


class UserTea_Cour(forms.ModelForm):
    class Meta:
        model = Tea_Cour
        fields = ['cno', 'cname', 'tno']
        widgets = {
            "cno": forms.TextInput(attrs={'class': "form-control", 'style': "width:90%;"'requ'}),
            "cname": forms.TextInput(attrs={'class': "form-control", 'style': "width:90%;"}),
            "tno": forms.TextInput(attrs={'class': "form-control", 'style': "width:90%;"}),
        }



# Select courses
def showCourse_tea(request):
    user = request.session.get('user')
    data_dict = {'tno': user}
    if request.method == "GET":
        cname = request.GET.get('cname', "")
        if cname:
            data_dict['cname'] = cname
        cno = request.GET.get('cno', "")
        if cno:
            data_dict['cno'] = cno
        # user_courses = Tea_Cour.objects.filter(tno=user).values_list('cname', flat=True)
        # 教师只能查看自己的课程，因此初始化tno
        form = UserTea_Cour(request.GET, initial={'tno': user})
        course = Tea_Cour.objects.filter(**data_dict)
        return render(request, 'show_course_tea.html', {'course': course, "form": form, "user": user})
    else:
        form = UserTea_Cour(initial={'tno': user})
        course = Tea_Cour.objects.filter(tno=user)
        return render(request, 'show_course_tea.html', {'course': course, "form": form, "user": user})


def addCourse_tea(request):
    user = request.session.get('user')
    if request.method == "GET":
        form = UserTea_Cour(initial={'tno': user})
        return render(request, 'add_course.html', {'form': form, "user": user})
    else:
        form = UserTea_Cour(request.POST)
        if form.is_valid():
            cname = form.cleaned_data.get('cname')
            tno = form.cleaned_data.get('tno')
            if tno != user:
                return render(request, 'add_course.html',
                              {'form': form, 'errormessage': "没有权限", "user": user})
            if Tea_Cour.objects.filter(cname=cname, tno=user).exists():
                return render(request, 'add_course.html',
                              {'form': form, 'errormessage': "课程信息已存在", "user": user})
            else:
                form.fields['tno'].initial = user
                form.save()
                return render(request, 'add_course.html', {'form': form, 'success': "课程信息添加成功", "user": user})
        else:
            return render(request, 'add_course.html', {'form': form, "user": user})


def deleteCourse_tea(request):
    cno = request.GET.get('cno')
    Tea_Cour.objects.filter(cno=cno).delete()
    return redirect('course_information_tea')


#

class UserHomework_ddl(forms.ModelForm):
    class Meta:
        model = Homework_ddl
        fields = ['cno', 'workno', 'homework_time', 'plateform']
        widgets = {
            "cno": forms.TextInput(attrs={'class': "form-control",'blank':"false", 'style': "width:90%; "}),
            "workno": forms.TextInput(attrs={'class': "form-control", 'blank':"false",'style': "width:90%;"}),
            "homework_time": forms.DateInput(attrs={'class': "form-control", 'blank':"false",'type': 'date', 'style': "width:90%;"}),
            "plateform": forms.TextInput(attrs={'class': "form-control", 'blank':"false",'style': "width:90%;",'placeholder':"形如教西A205"}),
        }

# Select homework
def showWork_tea(request):
    print(request.method)
    user = request.session.get('user')
    data_dict = {}
    if request.method == "GET":
        cno = request.GET.get('cno', "")
        workno = request.GET.get('workno', "")
        homework_time = request.GET.get(' homework_time', "")
        plateform = request.GET.get('plateform', "")
        cname = request.GET.get('cname', "")
        # 初始化声明homework
        homework = Homework_ddl.objects.none()
        if cno:
            data_dict['cno'] = cno
        if workno:
            data_dict['workno'] = workno
        if homework_time:
            data_dict['homework_time'] = homework_time
        if plateform:
            data_dict['plateform'] = plateform
        if cname:
            course_cno = Tea_Cour.objects.filter(cname=cname).values_list('cno', flat=True)
            homework = Homework_ddl.objects.filter(cno__in=course_cno, **data_dict)
        if not cname:
            homework = Homework_ddl.objects.filter(**data_dict)
            # 筛选考试信息
        course_names_dict = {course.cno: course.cname for course in Tea_Cour.objects.filter(tno=user)}
        form_work = UserHomework_ddl(request.GET)
        form_course = UserTea_Cour_Cname(request.GET)
        return render(request, 'show_work_tea.html',
                      {'homework': homework, 'cname': course_names_dict, "form_work": form_work,
                       "form_course": form_course, "user": user})


def addWork_tea(request):
    user = request.session.get('user')
    if request.method == "GET":
        cno = request.GET.get('cno', "")
        cname = request.GET.get('cname', "")
        form_homework = UserHomework_ddl(initial={'cno': cno})
        form_course = UserTea_Cour_Cname(initial={'cname': cname})
        return render(request, 'add_work.html',
                      {'form_homework': form_homework, 'form_course': form_course, "user": user})
    if request.method == "POST":
        form_homework = UserHomework_ddl(request.POST)
        form_course = UserTea_Cour_Cname(request.POST)
        print(request.POST)
        print(form_course.is_valid())
        print(form_homework.is_valid())
        if form_course.is_valid() and form_homework.is_valid():
            cname = form_course.cleaned_data.get('cname')
            cno = form_homework.cleaned_data.get('cno')
            workno = form_homework.cleaned_data.get('workno')
            if not Tea_Cour.objects.filter(cno=cno, cname=cname).exists():
                return render(request, 'add_work.html',
                              {'form_homework': form_homework, 'form_course': form_course,
                               'errormessage': "该课程不存在",
                               "user": user})
            if Homework_ddl.objects.filter(workno=workno).exists():
                return render(request, 'add_work.html',
                              {'form_homework': form_homework, 'form_course': form_course,
                               'errormessage': "作业已经存在",
                               "user": user})
            else:
                print("ok")
                form_homework.save()
                return render(request, 'add_work.html',
                              {'success': "作业已经发布！", 'form_homework': form_homework, 'form_course': form_course,
                               'user': user})
        else:
            return render(request, 'add_work.html',
                          {'form_homework': form_homework, 'form_course': form_course, "user": user})
    else:
        form_homework = UserHomework_ddl(request.POST)
        form_course = UserTea_Cour_Cname(request.POST)
        # 处理不支持的请求方法
        return render(request, 'add_work.html', {'form_work': form_homework, 'form_course': form_course, "user": user})


def deleteWork_tea(request):
    id = request.GET.get('id')
    Homework_ddl.objects.filter(id=id).delete()
    return redirect('work_information_tea')


# ####
# # 学生
# ####
#
class UserStu_Cour(forms.ModelForm):
    class Meta:
        model = Stu_Cour
        fields = ['cno', 'sno']
        widgets = {
            "cno": forms.TextInput(attrs={'class': "form-control", 'style': "width:90%;"}),
            "sno": forms.TextInput(attrs={'class': "form-control", 'style': "width:90%;", 'readonly': "readonly"}),
        }


# 学生课程查看(self)
# 已选课程
def showCourse_stu(request):
    user = request.session.get('user')
    data_dict = {}

    if request.method == "GET":
        cno = request.GET.get('cno', "")
        tno = request.GET.get('tno', "")
        cname = request.GET.get('cname', "")

        if cno:
            data_dict['cno'] = cno
        if tno:
            data_dict['tno'] = tno

        # 处理选课信息
        if cname:
            course_cno = Tea_Cour.objects.filter(cname=cname).values_list('cno', flat=True)
            selected_course = Stu_Cour.objects.filter(cno__in=course_cno, **data_dict)
        else:
            selected_course = Stu_Cour.objects.filter(**data_dict)

        form_course = UserTea_Cour(request.GET)

        # 获取最终的课程信息
        course_details = Tea_Cour.objects.filter(cno__in=selected_course.values_list('cno', flat=True))

        # 将课程信息与学生选课信息结合

        return render(request, 'show_course_stu.html', {
            'course_data': course_details,
            "form_course": form_course,
            "user": user
        })


# 学生选课功能
def select_course_stu(request):
    user = request.session.get('user')
    print(user)
    data_dict = {}
    if request.method == "GET":
        cno = request.GET.get('cno', "")
        tno = request.GET.get('tno', "")
        cname = request.GET.get('cname', "")
        if cname:
            data_dict['cname'] = cname
        if tno:
            data_dict['tno'] = tno
        if cno:
            data_dict['cno'] = cno
        form = UserTea_Cour(request.GET)
        course = Tea_Cour.objects.filter(**data_dict)
        return render(request, 'select_course_stu.html', {'course': course, "form": form, "user": user})
    else:
        form = UserTea_Cour()
        course = Tea_Cour.objects.all()
        return render(request, 'select_course_stu.html', {'course': course, "form": form, "user": user})


def select_course_select(request):
    cno = request.GET.get('cno')
    user = request.session.get('user')

    try:
        course = Tea_Cour.objects.get(cno=cno)
        cname = course.cname
    except Tea_Cour.DoesNotExist:
        messages.error(request, "课程号不存在。")
        return redirect('course_select_stu')

    # 获取该课程名下的所有课程号
    cname_all_cno = list(Tea_Cour.objects.filter(cname=cname).values_list('cno', flat=True))

    # 检查用户是否已经选择过该课程名下的任何课程号
    already_selected_courses = Stu_Cour.objects.filter(cno__in=cname_all_cno, sno=user)

    if already_selected_courses.exists():
        messages.error(request, "课程已经被选过了。")
    else:
        select_record = Stu_Cour(cno=cno, sno=user)
        select_record.save()
        messages.success(request, "选课成功。")

    return redirect('course_select_stu')


def delete_course_stu(request):
    user = request.session.get('user')
    cno = request.GET.get('cno')
    Stu_Cour.objects.filter(cno=cno, sno=user).delete()
    return redirect('course_information_stu')


def student_work(request):
    user = request.session.get('user')
    data_dict = {}
    if request.method == "GET":
        cno = request.GET.get('cno', "")
        workno = request.GET.get('workno', "")
        homework_time = request.GET.get('homework_time', "")
        plateform = request.GET.get('plateform', "")
        cname = request.GET.get('cname', "")

        if cno:
            data_dict['cno'] = cno
        if workno:
            data_dict['workno'] = workno
        if homework_time:
            data_dict['homework_time'] = homework_time
        if plateform:
            data_dict['plateform'] = plateform
        enrolled_courses = Stu_Cour.objects.filter(sno=user)

        if cname:
            course_cno = Tea_Cour.objects.filter(cname=cname).values_list('cno', flat=True)
            homework = Homework_ddl.objects.filter(cno__in=course_cno, **data_dict)
        else:
            homework = Homework_ddl.objects.filter(cno__in=[course.cno for course in enrolled_courses], **data_dict)

        # Fetch course names for displaying
        course_names = Tea_Cour.objects.filter(cno__in=[course.cno for course in enrolled_courses])
        course_names_dict = {course.cno: course.cname for course in course_names}

        context = {
            'homework': homework,
            'cname': course_names_dict
        }
        form_work = UserHomework_ddl(request.POST)
        return render(request, 'show_work_stu.html',
                      {"form_work": form_work, 'homework': homework, 'cname': course_names_dict, 'user': user})


def student_test(request):
    user = request.session.get('user')
    data_dict = {}
    if request.method == "GET":
        cno = request.GET.get('cno', "")

        test_time = request.GET.get('test_time', "")
        test_place = request.GET.get('test_place', "")
        cname = request.GET.get('cname', "")

        if cno:
            data_dict['cno'] = cno
        if test_time:
            data_dict['test_time'] = test_time
        if test_place:
            data_dict['test_place'] = test_place
        enrolled_courses = Stu_Cour.objects.filter(sno=user)
        if cname:
            course_cno = Tea_Cour.objects.filter(cname=cname).values_list('cno', flat=True)
            test = Test_ddl.objects.filter(cno__in=course_cno, **data_dict)
        else:
            test = Test_ddl.objects.filter(cno__in=[course.cno for course in enrolled_courses], **data_dict)

        # Fetch course names for displaying
        course_names = Tea_Cour.objects.filter(cno__in=[course.cno for course in enrolled_courses])
        course_names_dict = {course.cno: course.cname for course in course_names}

        form_test = UserTest(request.POST)
        return render(request, 'show_test_stu.html',
                      {"form_test": form_test, 'test': test, 'cname': course_names_dict, 'user': user})
